import { defineStore } from 'pinia';
import { ElMessage } from 'element-plus';

export const useCartStore = defineStore('cart', {
  state: () => ({
    items: []
  }),
  actions: {
    addItem(product) {
      // 检查商品是否已在购物车中
      const existingItem = this.items.find(item => item.id === product.id);
      
      if (existingItem) {
        // 如果已存在，增加数量
        existingItem.quantity++;
        ElMessage.success(`商品 ${product.name} 数量已更新`);
      } else {
        // 如果不存在，添加新商品，默认数量为1
        this.items.push({
          ...product,
          quantity: 1
        });
        ElMessage.success(`商品 ${product.name} 已添加到购物车`);
      }
    },
    removeItem(id) {
      this.items = this.items.filter(item => item.id !== id);
      ElMessage.success('商品已从购物车移除');
    },
    updateQuantity(id, quantity) {
      const item = this.items.find(item => item.id === id);
      if (item) {
        item.quantity = quantity;
      }
    },
    clearCart() {
      this.items = [];
      ElMessage.success('购物车已清空');
    }
  },
  getters: {
    totalItems() {
      return this.items.reduce((total, item) => total + item.quantity, 0);
    },
    totalAmount() {
      return this.items.reduce((total, item) => total + (item.price * item.quantity), 0).toFixed(2);
    }
  }
});